package com.example.activiti.common.exclusion;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;

/**
 * @author Administrator
 */
@Component
public class UserDetailsUtil {

    @Resource
    private UserDetailsServiceImpl selfUserDetailsService;

    public void loginAs(String userNameAndRole) {
        // 设置登录用户
        UserDetails user = selfUserDetailsService.loadUserByUsername(userNameAndRole);
        if (user == null) {
            throw new IllegalStateException("User " + userNameAndRole + " doesn't exist, please provide a valid user");
        }
        // 设置上下文
        SecurityContextHolder.setContext(
                new SecurityContextImpl(
                        new Authentication() {
                            @Override
                            public Collection<? extends GrantedAuthority> getAuthorities() {
                                return user.getAuthorities();
                            }

                            @Override
                            public Object getCredentials() {
                                return user.getPassword();
                            }

                            @Override
                            public Object getDetails() {
                                return user;
                            }

                            @Override
                            public Object getPrincipal() {
                                return user;
                            }

                            @Override
                            public boolean isAuthenticated() {
                                return true;
                            }

                            @Override
                            public void setAuthenticated(boolean b) throws IllegalArgumentException {
                            }

                            @Override
                            public String getName() {
                                return user.getUsername();
                            }
                        }
                )
        );
        org.activiti.engine.impl.identity.Authentication.setAuthenticatedUserId(userNameAndRole);
    }
}
